/* -*- Mode:C++; c-file-style:"gnu"; indent-tabs-mode:nil; -*- */
/*
 * Copyright (c) 2011 SMUNIX
 *
 * This program is free software; you can redistribute it and/or modify
 * it under the terms of the GNU General Public License version 2 as
 * published by the Free Software Foundation;
 *
 * This program is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU General Public License for more details.
 *
 * You should have received a copy of the GNU General Public License
 * along with this program; if not, write to the Free Software
 * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA
 *
 * Author: Providence M. Salumu <providence.salumu@smunix.com>
 */

#include "test.hpp"
#include <slib/acceptor.hpp>
#include <slib/singleton.hpp>
#include <memory>

struct IOne
{
  virtual ~IOne (void) {}
  virtual void One (void) = 0;
};

struct ITwo
{
  virtual ~ITwo (void) {}
  virtual void Two (void) = 0;
};

struct Callback : public smunix::Singleton<Callback>
{
  Callback () : mValue (0) {}
  int mValue;
  int Value() const { return mValue; }
  void Value(int val) { mValue = val; }
};

struct OneType : public IOne, smunix::Acceptor<ITwo>
{
  typedef std::shared_ptr<OneType> SP;
  virtual ~OneType (void) {}
  virtual void One (void)
  {
    Callback::Instance ().Value (1 + Callback::Instance ().Value ());
  }
  void Invoke (void)
  {
    Peek(ITwo)->Two ();
  }
};

struct TwoType : public ITwo, smunix::Acceptor<IOne>
{
  typedef std::shared_ptr<TwoType> SP;
  virtual ~TwoType (void) {}
  virtual void Two (void)
  {
    Callback::Instance ().Value (1 + Callback::Instance ().Value ());
  }
  void Invoke (void)
  {
    Peek(IOne)->One ();
  }
};

struct Fixture
{
  Fixture (void)
  {
    one.reset (new OneType);
    two.reset (new TwoType);

    one->Pack (ITwo, two);
    two->Pack (IOne, one);
  }
  virtual ~Fixture (void)
  {
    one.reset ();
    two.reset ();
  }
  OneType::SP one;
  TwoType::SP two;
};

BOOST_FIXTURE_TEST_SUITE (space, Fixture)
BOOST_AUTO_TEST_CASE (SymmetricCall)
{
  one->One ();
  BOOST_CHECK_EQUAL (Callback::Instance ().Value (), 1);
  one->Invoke ();
  BOOST_CHECK_EQUAL (Callback::Instance ().Value (), 2);
  one->Peek (ITwo)->Two ();
  BOOST_CHECK_EQUAL (Callback::Instance ().Value (), 3);

  two->Two ();
  BOOST_CHECK_EQUAL (Callback::Instance ().Value (), 4);
  two->Invoke ();
  BOOST_CHECK_EQUAL (Callback::Instance ().Value (), 5);
  two->Peek (IOne)->One ();
  BOOST_CHECK_EQUAL (Callback::Instance ().Value (), 6);
}
BOOST_AUTO_TEST_SUITE_END ()

